/*
 * 
 */
package com.asgard.utils;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;

public class CertificateUtils {
    /**
     * 将X509Certificate保存成文件 <br>
     *
     * 自动添加-----BEGIN CERTIFICATE-----\n \n-----END CERTIFICATE-----
     * 
     * @param cert
     * @param path
     * @throws CertificateEncodingException
     */
    public static void saveAsFile(Certificate cert, String path) throws CertificateEncodingException {
        try {
            OutputStream os = new FileOutputStream(path);
            OutputStreamWriter osw = new OutputStreamWriter(os);
            String base64string = "-----BEGIN CERTIFICATE-----\n" + Base64.encode(cert.getEncoded())
                    + "\n-----END CERTIFICATE-----";
            osw.write(base64string);
            osw.flush();
            osw.close();
            os.flush();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将base64 string转换成X509证书 <br>
     * 自动添加-----BEGIN CERTIFICATE-----\n \n-----END CERTIFICATE-----
     * 
     * @param certB64
     * @return
     * @throws CertificateException
     * @throws NoSuchProviderException
     */
    public static X509Certificate decode(String certB64) throws CertificateException, NoSuchProviderException {
        final String BEGIN = "-----BEGIN CERTIFICATE-----\n";
        final String END = "\n-----END CERTIFICATE-----";
        String base64 = certB64.substring(certB64.indexOf(BEGIN) + BEGIN.length(), certB64.lastIndexOf(END));
        byte encodedCert[] = Base64.decode(base64);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(encodedCert);
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
        return cert;
    }

    public static String encode(X509Certificate cert) throws CertificateEncodingException {
        return "-----BEGIN CERTIFICATE-----\n" + Base64.toBase64String(cert.getEncoded()) + "\n-----END CERTIFICATE-----";
    }

    /**
     * 从文件加载证书
     * 
     * 不自动添加-----BEGIN CERTIFICATE-----\n \n-----END CERTIFICATE-----
     * 
     * @param path
     * @return
     */
    public static X509Certificate getFromPath(String path) {
        FileInputStream is = null;
        CertificateFactory certificateFactory = null;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
            is = new FileInputStream(path);
            X509Certificate rootX509Certificate = null;
            try {
                rootX509Certificate = (X509Certificate) certificateFactory.generateCertificate(is);
            } catch (CertificateException e) {
                e.printStackTrace();
            }
            return rootX509Certificate;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e1) {
            e1.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                is = null;
            }
        }
        return null;
    }

    public static void main(String[] args) throws CertificateException, FileNotFoundException, Exception {
        ClassicCryptoService l = new ClassicCryptoService();
        System.out.println(l);
//      String file = "I:/ROOT_CA.crt";
//      InputStream inputStream = new FileInputStream(file);
//      CertificateFactory certFactory = CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME);
//      X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
//      System.out.println(cert);
      String cert = "-----BEGIN CERTIFICATE-----\n"
              + "MIIB0jCCAXigAwIBAgIDAYbVMAoGCCqGSM49BAMCMCQxIjAgBgNVBC4TGUFTR0FSRF9CTE9DS0NI\n"
              + "QUlOX1JPT1RfQ0EwHhcNMjAwNDE3MDM0NjI2WhcNMzAwNDE3MDM1NjI2WjANMQswCQYDVQQDDAJE\n"
              + "TjBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJpqHXzkTtD2VGT/DODARilwZpxdevN5NIclRy6m\n"
              + "1aZZ6wgX8b1jUOUlwRdjoTGb9wkzZccxxmsQnG1zqCmH5lOjga8wgawwKQYDKgYDBCIMIDU5OTA0\n"
              + "YzkyZDA3NjQxNzk5YWI0ZGE0OWZlZDM4NzI1MBMGAyoGAQQMDApDT05ORUNUSU9OMAsGAyoGAgQE\n"
              + "DAJWUDAtBgMqBgUEJgwkNDBiNjMzYjAtODVmZi00YjU0LWIzZDUtNmY1ZDZkZDFiMmY5MAoGAyoG\n"
              + "BAQDDAEwMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA0gA\n"
              + "MEUCIQDmjsdEbGYpMZOGnEy1KV/tUI1lML3ib4RksHSBiIag4AIgDuDJfSjDlcKIubW8a9PabhZI\n"
              + "q/WDvkoglZPixnwSBu4=\n" + "-----END CERTIFICATE-----";
      X509Certificate decode = decode(cert);
      System.out.println(decode.getSigAlgName());
      
      String x509Str = encode(decode);
      System.out.println(x509Str);
  }

}

// end
